﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Sripirom.ATS.Core.Messaging;

namespace Sripirom.ATS.Core.ServiceModel.Dispatcher
{
    /// <summary>
    /// Represents a message inspector object that can be added to the <c>MessageInspectors</c> collection to view or modify messages.
    /// </summary>
    public class MessageInspector : IClientMessageInspector, IDispatchMessageInspector
    {


        #region IClientMessageInspector

        /// <summary>
        /// Enables inspection or modification of a message before a request message is sent to a service.
        /// </summary>
        /// <param name="request">The message to be sent to the service.</param>
        /// <param name="channel">The WCF client object channel.</param>
        /// <returns>
        /// The object that is returned as the <paramref name="correlationState " /> argument of
        /// the <see cref="M:System.ServiceModel.Dispatcher.IClientMessageInspector.AfterReceiveReply(System.ServiceModel.Channels.Message@,System.Object)" /> method.
        /// This is null if no correlation state is used.The best practice is to make this a <see cref="T:System.Guid" /> to ensure that no two
        /// <paramref name="correlationState" /> objects are the same.
        /// </returns>
        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
            //ServiceMessageHeader header = new ServiceMessageHeader();

            //request.Headers.Add(header);

            return null;// header.TransactionId;
        }

        /// <summary>
        /// Enables inspection or modification of a message after a reply message is received but prior to passing it back to the client application.
        /// </summary>
        /// <param name="reply">The message to be transformed into types and handed back to the client application.</param>
        /// <param name="correlationState">Correlation state data.</param>
        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            
        }

        #endregion

        #region IDispatchMessageInspector
        //public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        //{
        //    ServiceMessageHeader customData = ServiceHeader.ReadHeader(request);

        //    String channelRequest = System.ServiceModel.OperationContext.Current.RequestContext.RequestMessage.ToString();

        //    //return customData;

        //    return null;
        //}

        //public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        //{
        //    ServiceMessageHeader header = ServiceHeader.ReadHeader(reply);

        //   // String channelReply = System.ServiceModel.OperationContext.Current.

        //    //reply.Headers.Add(new ServiceMessageHeader() { TransactionId = "000001" });
        //}
        #region

        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            ServiceMessageHeader header = ServiceHeader.ReadHeader(request);

            string ChanelRequest = request.ToString();
           string  TransactionId = header.TransactionId;
           string ChannelCode = header.ChannelId;
           //string Status = ServiceStatus.EX;


            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml(ChanelRequest);
            XmlNamespaceManager ns = new XmlNamespaceManager(xmldoc.NameTable);
            ns.AddNamespace("body", request.Headers.Action + "/RequestMessage/Body");

            string CompanyCode = xmldoc.SelectSingleNode("//body:CompanyCode", ns).InnerText;
            string ServiceCode = xmldoc.SelectSingleNode("//body:ServiceCode", ns).InnerText;
            string SubServiceCode = xmldoc.SelectSingleNode("//body:SubServiceCode", ns).InnerText;
            string TranferType = xmldoc.SelectSingleNode("//body:TranferType", ns).InnerText;


            return null;
        }

        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml(reply.ToString());
            XmlNamespaceManager ns = new XmlNamespaceManager(xmldoc.NameTable);
           // ns.AddNamespace("", "http://www.kiatnakinbank.com/services/ATS/IInquiryService/InquiryDecision/ResponseMessage/Body");
           // ns.AddNamespace("i", "http://www.w3.org/2001/XMLSchema-instance");
            ns.AddNamespace("out", "http://www.kiatnakinbank.com/services/ATS/MessageOutput");

            //XmlObjectSerializer serializer = new DataContractSerializer(typeof(MessageOutput), "Output", "http://www.kiatnakinbank.com/services/ATS/IInquiryService/InquiryDecision/ResponseMessage/Output", null, Int32.MaxValue, false, false, null);
            //MessageOutput output =  reply.GetBody<MessageOutput>(serializer);

                           
            //var Output = new MessageOutput()
            //{
            string Result = xmldoc.SelectSingleNode("//out:Result", ns).InnerText;
            string ErrorReason = xmldoc.SelectSingleNode("//out:ErrorReason", ns).InnerText;
            //};
            //CompanyCode = xmldoc.SelectSingleNode("//body:CompanyCode", ns).InnerText;
            //ServiceCode = xmldoc.SelectSingleNode("//body:ServiceCode", ns).InnerText;
            //SubServiceCode = xmldoc.SelectSingleNode("//body:SubServiceCode", ns).InnerText;
            //TranferType = xmldoc.SelectSingleNode("//body:TranferType", ns).InnerText;

        }

        #endregion
        #endregion
    }
}
